package com.bls.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bls.dao.*;
import com.bls.dao.impl.*;
import com.bls.entity.*;
import com.bls.entity.query.DraftQuery;
import com.bls.entity.vo.DraftVo;
import com.bls.entity.vo.RunScriptVo;
import com.bls.executor.environment.MyMQ;
import com.bls.executor.environment.threadPool.ThreadPoolGroup;
import com.bls.remote.service.CoreRemoteService;
import com.bls.remote.service.IMessageToolRemoteService;
import com.bls.remote.service.impl.CoreRemoteServiceImpl;
import com.bls.remote.service.impl.MessageToolRemoteServiceImpl;
import com.bls.service.*;
import com.bls.service.impl.*;
import com.bls.utils.BandCore;
import com.bls.utils.JedisUtil;
import com.bls.utils.JsonUtils;
import com.bls.utils.R;
import com.fy.basejar.tool.ActionToolBase;
import com.fy.toolhelper.util.RequestUtils;
import com.rabbitmq.client.Channel;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;

/**
 * 新的Controller  -- BLSAction
 *
 * @author xiaoliang
 * @date 2022/01/11 11:00
 **/
public class BLSAction extends ActionToolBase {

    /**
     * 获取暴露给前端的一些配置信息
     */
    @Action
    public Map<String, Object> getConfigs() {
        // 建议如果需要向前端暴露一些后台的配置或运行环境信息时, 可以通过这样一个action接口来实现. 比如当前用户的具体信息等等.
        return new HashMap<String, Object>();
    }

    /*
    *  objId 转化为 bandId
    * */
    public Long objIdToBandId(Long objId) throws Exception {
        CoreRemoteService coreRemoteService = getBean(CoreRemoteService.class);
        Map<String, Object> band = coreRemoteService.getBandByBandObjId(objId);
        if(band == null) return objId;
        Long bandId = Long.valueOf((String) band.get("realObjID"));
        return bandId;
    }

    /**
     * 添加剧本草稿
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R addDraft(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        ActionLogService actionLogService = getBean(ActionLogService.class);
        JSONObject jsonParam = JSONObject.parseObject(RequestUtils.getStringParameter(request, "draft"));
        Draft draft = JsonUtils.getJavaObject(jsonParam, Draft.class);

        Date date = new Date();

        // 添加操作记录，用于展示动态
        ActionLog actionLog = new ActionLog();
        actionLog.setUserId(draft.getCreatorId());
        actionLog.setUserName(draft.getCreatorName());
        // objId 转化为 bandId
        actionLog.setBandId(objIdToBandId(draft.getBandId()));
        actionLog.setBandName(draft.getBandName());
        actionLog.setAction("添加");
        actionLog.setObject(draft.getName());
        actionLog.setType("剧本草稿");
        actionLog.setTime(date);
        actionLogService.save(actionLog);

        // 保存剧本草稿
        draft.setCreateTime(date);
        draft.setUpdateTime(date);
        // objId 转化为 bandId
        draft.setBandId(objIdToBandId(draft.getBandId()));
        draftService.save(draft);
        return R.ok().message("添加剧本草稿成功");
    }

    /**
     * 删除剧本草稿
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R deleteDraft(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        ActionLogService actionLogService = getBean(ActionLogService.class);
        Long draftId = RequestUtils.getLongParameter(request, "draftId");
        Long userId = RequestUtils.getLongParameter(request, "userId");
        String userName = RequestUtils.getStringParameter(request, "userName");

        Draft draft = draftService.selectDraftById(draftId);

        Date date = new Date();
        // 添加`删除操作`记录，用于展示动态
        ActionLog actionLog = new ActionLog();
        actionLog.setUserId(userId);
        actionLog.setUserName(userName);
        actionLog.setBandId(draft.getBandId());
        actionLog.setBandName(draft.getBandName());
        actionLog.setAction("删除");
        actionLog.setObject(draft.getName());
        actionLog.setType("剧本草稿");
        actionLog.setTime(date);
        actionLogService.save(actionLog);

        int i = draftService.deleteDraft(draftId);
        return i == -1 ? R.error().message("删除剧本草稿失败") : R.ok().message("删除剧本草稿成功");
    }

    /**
     * 修改剧本草稿
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R updateDraft(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        JSONObject jsonParam = JSONObject.parseObject(RequestUtils.getStringParameter(request, "updateDraft"));
        Draft draft = JsonUtils.getJavaObject(jsonParam, Draft.class);
        draft.setUpdateTime(new Date());
        int i = draftService.updateDraft(draft);

        return i == 0 ? R.error().message("修改剧本草稿失败") : R.ok().message("修改剧本草稿成功");
    }


    /**
     * 分页条件查询剧本草稿列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R pageConditionDraftList(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "draftQuery"));
        DraftQuery draftQuery = JsonUtils.getJavaObject(jsonString, DraftQuery.class);
        if(draftQuery.getBandId() != 0){
            draftQuery.setBandId(objIdToBandId(draftQuery.getBandId()));
        }
        JSONObject pageInfo = JSONObject.parseObject(RequestUtils.getStringParameter(request, "pageInfo"));
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer currentPage = (Integer) pageInfo.get("currentPage");
        List<DraftVo> draftList = null;
        try {
            draftList = draftService.pageConditionDraftList(draftQuery, pageSize, currentPage);
        } catch (Exception e) {
            return R.ok().message(e.getMessage());
        }
        Integer total = draftService.pageConditionDraftTotal(draftQuery);
        return R.ok().put("rows", draftList).put("total", total).message("分页条件查询剧本草稿列表，查询成功");
    }

    /**
     * 添加分析剧本
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R addAnalyse(HttpServletRequest request) throws Exception {
        AnalyseService analyseService = getBean(AnalyseService.class);
        ActionLogService actionLogService = getBean(ActionLogService.class);
        Long draftId = RequestUtils.getLongParameter(request, "draftId");
        JSONObject jsonParam = JSONObject.parseObject(RequestUtils.getStringParameter(request, "analyse"));
        Analyse analyse = JsonUtils.getJavaObject(jsonParam, Analyse.class);

        Date date = new Date();
        // 添加`添加分析剧本操作`记录，用于展示动态
        ActionLog actionLog = new ActionLog();
        actionLog.setUserId(analyse.getDeveloperId());
        actionLog.setUserName(analyse.getDeveloperName());
        actionLog.setBandId(objIdToBandId(analyse.getBandId()));
        actionLog.setBandName(analyse.getBandName());
        actionLog.setAction("添加");
        actionLog.setObject(analyse.getCode());
        actionLog.setType("分析剧本");
        actionLog.setTime(date);
        actionLogService.save(actionLog);

        // 保存分析剧本
        analyse.setCreateTime(date);
        analyse.setUpdateTime(date);
        analyse.setBandId(objIdToBandId(analyse.getBandId()));
        analyseService.save(draftId, analyse);
        return R.ok().message("添加分析剧本成功");
    }

    /**
     * 查看已开发的分析剧本
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R getAnalyse(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "draftQuery"));
        DraftQuery draftQuery = JsonUtils.getJavaObject(jsonString, DraftQuery.class);
        if(draftQuery.getBandId() != 0){
            draftQuery.setBandId(objIdToBandId(draftQuery.getBandId()));
        }
        List<DraftVo> draftVos = draftService.pageConditionAnalyseRunningStatusList(draftQuery,1,1);
        return R.ok().put("rows", draftVos).put("total", draftVos.size()).message("查询已开发草稿剧本信息成功");
    }

    /**
     * 修改已开发的分析剧本
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R updateAnalyse(HttpServletRequest request) throws Exception {
        AnalyseService analyseService = getBean(AnalyseService.class);
        ActionLogService actionLogService = getBean(ActionLogService.class);

        String code = RequestUtils.getStringParameter(request, "code");
        Long analyseId = RequestUtils.getLongParameter(request, "analyseId");

        Analyse analyseInfo = analyseService.selectAnalyseById(analyseId);

        Long userId = RequestUtils.getLongParameter(request, "userId");
        String userName = RequestUtils.getStringParameter(request, "userName");

        Date date = new Date();

        // 添加`修改分析剧本操作`记录，用于展示动态
        ActionLog actionLog = new ActionLog();
        actionLog.setUserId(userId);
        actionLog.setUserName(userName);
        actionLog.setBandId(analyseInfo.getBandId());
        actionLog.setBandName(analyseInfo.getBandName());
        actionLog.setAction("修改");
        actionLog.setObject(code);
        actionLog.setType("分析剧本");
        actionLog.setTime(date);
        actionLogService.save(actionLog);

        Analyse analyse = new Analyse();
        analyse.setId(analyseId);
        analyse.setCode(code);
        analyse.setUpdateTime(date);
        int i = analyseService.updateAnalyse(analyse);

        return i == 0 ? R.error().message("修改分析剧本失败") : R.ok().message("修改分析剧本成功");
    }

    /**
     * 查看运行记录 Draft Analyse
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R pageConditionAnalyseRunningStatusList(HttpServletRequest request) throws Exception {
        DraftService draftService = getBean(DraftService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "draftQuery"));
        DraftQuery draftQuery = JsonUtils.getJavaObject(jsonString, DraftQuery.class);
        if(draftQuery.getBandId() != 0){
            draftQuery.setBandId(objIdToBandId(draftQuery.getBandId()));
        }
        JSONObject pageInfo = JSONObject.parseObject(RequestUtils.getStringParameter(request, "pageInfo"));
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer currentPage = (Integer) pageInfo.get("currentPage");
        List<DraftVo> draftList = null;
        try {
            draftList = draftService.pageConditionAnalyseRunningStatusList(draftQuery, pageSize, currentPage);
        } catch (Exception e) {
            return R.ok().message(e.getMessage());
        }
        Integer total = draftService.pageConditionAnalyseRunningStatusTotal(draftQuery);
        return R.ok().put("rows", draftList).put("total", total).message("分页条件查询分析剧本运行状态列表，查询成功");
    }

    /**
     * 分页条件查询分析剧本运行记录列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R pageConditionHistoryRecordList(HttpServletRequest request) throws Exception {
        HistoryRecordService historyRecordService = getBean(HistoryRecordService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "historyRecordQuery"));
        HistoryRecord historyRecordQuery = JsonUtils.getJavaObject(jsonString, HistoryRecord.class);
        if(historyRecordQuery.getBandId() != 0){
            historyRecordQuery.setBandId(objIdToBandId(historyRecordQuery.getBandId()));
        }
        JSONObject pageInfo = JSONObject.parseObject(RequestUtils.getStringParameter(request, "pageInfo"));
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer currentPage = (Integer) pageInfo.get("currentPage");
        List<HistoryRecord> historyRecordList = null;
        try {
            historyRecordList = historyRecordService.pageConditionHistoryRecordList(historyRecordQuery, pageSize, currentPage);
        } catch (Exception e) {
            return R.ok().message(e.getMessage());
        }
        Integer total = historyRecordService.pageConditionHistoryRecordTotal(historyRecordQuery);
        return R.ok().put("rows", historyRecordList).put("total", total).message("分页条件查询分析剧本历史记录列表，查询成功");
    }

    /**
     * 分页条件查询操作日志表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R pageConditionActionLogList(HttpServletRequest request) throws Exception {
        ActionLogService actionLogService = getBean(ActionLogService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "actionLogQuery"));
        ActionLog actionLogQuery = JsonUtils.getJavaObject(jsonString, ActionLog.class);
        if(actionLogQuery.getBandId() != 0){
            actionLogQuery.setBandId(objIdToBandId(actionLogQuery.getBandId()));
        }
        JSONObject pageInfo = JSONObject.parseObject(RequestUtils.getStringParameter(request, "pageInfo"));
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer currentPage = (Integer) pageInfo.get("currentPage");
        List<ActionLog> actionLogList = null;
        try {
            actionLogList = actionLogService.pageConditionActionLogList(actionLogQuery, pageSize, currentPage);
        } catch (Exception e) {
            return R.ok().message(e.getMessage());
        }
        Integer total = actionLogService.pageConditionActionLogListTotal(actionLogQuery);
        return R.ok().put("rows", actionLogList).put("total", total).message("分页条件查询操作日志列表，查询成功");
    }

    /**
     * 分页条件查询g4规则模板列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Action
    public R pageConditionG4List(HttpServletRequest request) throws Exception {
        G4Service g4Service = getBean(G4Service.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "g4Query"));
        G4 g4Query = JsonUtils.getJavaObject(jsonString, G4.class);
        JSONObject pageInfo = JSONObject.parseObject(RequestUtils.getStringParameter(request, "pageInfo"));
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer currentPage = (Integer) pageInfo.get("currentPage");
        List<G4> g4List = null;
        try {
            g4List = g4Service.pageConditionG4List(g4Query, pageSize, currentPage);
        } catch (Exception e) {
            return R.ok().message(e.getMessage());
        }
        Integer total = g4Service.pageConditionG4Total(g4Query);
        return R.ok().put("rows", g4List).put("total", total).message("分页条件查询g4规则模板列表，查询成功");
    }

    @Action
    public R getOrganizationAndBands(HttpServletRequest request) throws Exception {
        String bandId = "";
        try {
            bandId = RequestUtils.getStringParameter(request, "bandId");
        } catch (Exception e) {
            return R.error().message("参数名称异常");
        }
        AllEnvironmentService environmentService = getBean(AllEnvironmentService.class);
        Map<String, Object> organizationAndBands = environmentService.getOrganizationAndBands(Long.valueOf(bandId));
        return R.ok().put("rows", organizationAndBands).message("返回用户所在机构与其所在所有帮区");
    }

    @Action
    public R getAllEnvironment(HttpServletRequest request) throws Exception {
        AllEnvironmentService environmentService = getBean(AllEnvironmentService.class);
        String bandId = "";
        Long organizationId = null;
        try {
            bandId = RequestUtils.getStringParameter(request, "bandId");
            organizationId = environmentService.getOrganizationIdByBandId(Long.valueOf(bandId));
            if(organizationId == null) return R.error().message("机构id获取失败");
        } catch (Exception e) {
            return R.error().message("参数名称异常");
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("organizationEnvironment", environmentService.getOrganizationEnvironment(Long.valueOf(organizationId)));
        result.put("bandEnvironment", environmentService.getBandEnvironment(Long.valueOf(bandId), Long.valueOf(bandId)));
        return R.ok().put("rows", result).message("返回（机构、帮区、剧本）语境成功");
    }


    // --------------------------------------------------------------------------------------------------
    /*
     *  帮语解析执行
     * */
    public static Map<String, List<Future>> scriptRunningStatus = new Hashtable<>();
    public static Map<String, Map<String, Channel>> mqRunningStatus = new Hashtable<>();

    private List<RunScriptVo> getRunScriptVo(String scripts, long analyseId) throws Exception {
        List<RunScriptVo> runScriptVoList = new ArrayList<>();
        if (scripts != null) {
            runScriptVoList = JSON.parseObject(scripts, new TypeReference<List<RunScriptVo>>() {
            });
        } else {
            AnalyseService analyseService = getBean(AnalyseService.class);
            Analyse analyse = analyseService.selectAnalyseById(analyseId);
            String code = analyse.getCode();
            String[] scriptList = code.split("。");
            for (int i = 0; i < scriptList.length; i++) {
                RunScriptVo runScriptVo = new RunScriptVo();
                runScriptVo.setScript(scriptList[i] + "。");
                runScriptVo.setLine(String.valueOf(i + 1));
                runScriptVoList.add(runScriptVo);
            }
        }
        return runScriptVoList;
    }

    @Action
    public R runScript(HttpServletRequest request) throws Exception {
        ActionLogService actionLogService = getBean(ActionLogService.class);
        AnalyseService analyseService = getBean(AnalyseService.class);
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "historyRecord"));
        HistoryRecord historyRecord = JsonUtils.getJavaObject(jsonString, HistoryRecord.class);

        long analyseId = historyRecord.getAnalyseId();
        long bandId = historyRecord.getBandId();

        List<RunScriptVo> runScriptVoList = getRunScriptVo(null, analyseId);
        ScriptService scriptService = getBean(ScriptService.class);
        Map<String,Object> result = scriptService.runScript(runScriptVoList, bandId, analyseId);

        HistoryRecordService historyRecordService = getBean(HistoryRecordService.class);
        historyRecordService.save(historyRecord);

        Analyse analyseDB = analyseService.selectAnalyseById(analyseId);
        Date date = new Date();
        // 添加`运行分析剧本操作`记录，用于展示动态
        ActionLog actionLog = new ActionLog();
        actionLog.setUserId(historyRecord.getStartUserId());
        actionLog.setUserName(historyRecord.getStartUserName());
        actionLog.setBandId(bandId);
        actionLog.setBandName(historyRecord.getBandName());
        actionLog.setAction("运行");
        actionLog.setObject(analyseDB.getCode());
        actionLog.setType("分析剧本");
        actionLog.setTime(date);
        actionLogService.save(actionLog);


        if (scriptRunningStatus.containsKey(String.valueOf(analyseId))) {
            // 线程Map中有，表示非即时型Stmt,更改对应分析剧本的运行状态
            Analyse analyse = new Analyse();
            analyse.setId(analyseId);
            // 分析剧本运行状态（0-未运行，1-运行中）
            analyse.setStatus(1);
            analyseService.updateAnalyse(analyse);
        }

        if (mqRunningStatus.containsKey(String.valueOf(analyseId))) {
            // 线程Map中有，表示非即时型Stmt,更改对应分析剧本的运行状态
            Analyse analyse = new Analyse();
            analyse.setId(analyseId);
            // 分析剧本运行状态（0-未运行，1-运行中）
            analyse.setStatus(1);
            analyseService.updateAnalyse(analyse);
        }

        return R.ok().put(result);
    }

    @Action
    public R cancelScript(HttpServletRequest request) throws Exception {
        JSONObject jsonString = JSONObject.parseObject(RequestUtils.getStringParameter(request, "historyRecord"));
        HistoryRecord history = JsonUtils.getJavaObject(jsonString, HistoryRecord.class);
        long analyseId = history.getAnalyseId();

        if (scriptRunningStatus.containsKey(String.valueOf(analyseId))) {
            // 线程Map中有，表示非即时型Stmt 正在运行中，可以去停用
            List<Future> tasks = scriptRunningStatus.remove(String.valueOf(analyseId));
            for (Future task : tasks) {
                System.out.println("停用剧本。。。" + task);
                task.cancel(true);
            }

            // TODO 更新分析剧本（停止）运行记录 HistoryRecord
            // solved 找对应分析剧本id的最新的开始运行时间来更新结束时间
            HistoryRecordService historyRecordService = getBean(HistoryRecordService.class);
            HistoryRecord historyRecord = historyRecordService.getLastHistoryRecord(analyseId);
            historyRecord.setStopUserId(history.getStopUserId());
            historyRecord.setStopUserName(history.getStopUserName());
            historyRecordService.update(historyRecord);

            // 更改对应分析剧本的运行状态
            AnalyseService analyseService = getBean(AnalyseService.class);
            Analyse analyse = new Analyse();
            analyse.setId(analyseId);
            // 分析剧本运行状态（0-未运行，1-运行中）
            analyse.setStatus(0);
            analyseService.updateAnalyse(analyse);

            ActionLogService actionLogService = getBean(ActionLogService.class);
            Analyse analyseDB = analyseService.selectAnalyseById(analyseId);
            Date date = new Date();
            // 添加`停用分析剧本操作`记录，用于展示动态
            ActionLog actionLog = new ActionLog();
            actionLog.setUserId(historyRecord.getStartUserId());
            actionLog.setUserName(historyRecord.getStartUserName());
            actionLog.setBandId(historyRecord.getBandId());
            actionLog.setBandName(historyRecord.getBandName());
            actionLog.setAction("停用");
            actionLog.setObject(analyseDB.getCode());
            actionLog.setType("分析剧本");
            actionLog.setTime(date);
            actionLogService.save(actionLog);

            return R.ok().message("停用剧本成功");
        }
        if (mqRunningStatus.containsKey(String.valueOf(analyseId))) {
            // 线程Map中有，表示非即时型Stmt 正在运行中，可以去停用
            Map<String, Channel> mqConsumer = mqRunningStatus.remove(String.valueOf(analyseId));
            for (Map.Entry<String, Channel> tag : mqConsumer.entrySet()) {
                System.out.println("停用剧本。。。" + tag);
                Channel channel = tag.getValue();
                try {
                    channel.basicCancel(tag.getKey());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // TODO 更新分析剧本（停止）运行记录 HistoryRecord
            // solved 找对应分析剧本id的最新的开始运行时间来更新结束时间
            HistoryRecordService historyRecordService = getBean(HistoryRecordService.class);
            HistoryRecord historyRecord = historyRecordService.getLastHistoryRecord(analyseId);
            historyRecord.setStopUserId(history.getStopUserId());
            historyRecord.setStopUserName(history.getStopUserName());
            historyRecordService.update(historyRecord);

            // 更改对应分析剧本的运行状态
            AnalyseService analyseService = getBean(AnalyseService.class);
            Analyse analyse = new Analyse();
            analyse.setId(analyseId);
            // 分析剧本运行状态（0-未运行，1-运行中）
            analyse.setStatus(0);
            analyseService.updateAnalyse(analyse);

            ActionLogService actionLogService = getBean(ActionLogService.class);
            Analyse analyseDB = analyseService.selectAnalyseById(analyseId);
            Date date = new Date();
            // 添加`停用分析剧本操作`记录，用于展示动态
            ActionLog actionLog = new ActionLog();
            actionLog.setUserId(historyRecord.getStartUserId());
            actionLog.setUserName(historyRecord.getStartUserName());
            actionLog.setBandId(historyRecord.getBandId());
            actionLog.setBandName(historyRecord.getBandName());
            actionLog.setAction("停用");
            actionLog.setObject(analyseDB.getCode());
            actionLog.setType("分析剧本");
            actionLog.setTime(date);
            actionLogService.save(actionLog);

            return R.ok().message("停用剧本成功");
        }
        return R.ok().message("当前剧本已处于停用状态");
    }

    @Action
    public R deBugScript(HttpServletRequest request) throws Exception {
        String scripts = RequestUtils.getStringParameter(request, "scripts");
//        String bandId = RequestUtils.getStringParameter(request, "bandId");
        List<RunScriptVo> runScriptVoList = getRunScriptVo(scripts, -1);
        ScriptService scriptService = getBean(ScriptService.class);
        Map<String,Object> result = scriptService.deBugScript(runScriptVoList, -1, -1);
        return R.ok().put(result);
    }

    @Action
    public R cancelDeBugScript(HttpServletRequest request) throws Exception {
        if (scriptRunningStatus.containsKey(String.valueOf(-1))) {
            // 线程Map中有，表示非即时型Stmt 正在运行中，可以去停用
            List<Future> tasks = scriptRunningStatus.remove(String.valueOf(-1));
            for (Future task : tasks) {
                task.cancel(true);
            }
            return R.ok().message("停用剧本成功(调试)");
        }
        if (mqRunningStatus.containsKey(String.valueOf(-1))) {
            // 线程Map中有，表示非即时型Stmt 正在运行中，可以去停用
            Map<String, Channel> mqConsumer = mqRunningStatus.remove(String.valueOf(-1));
            for (Map.Entry<String, Channel> tag : mqConsumer.entrySet()) {
                System.out.println("停用剧本。。。" + tag);
                Channel channel = tag.getValue();
                try {
                    channel.basicCancel(tag.getKey());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return R.ok().message("停用剧本成功(调试)");
        }
        return R.ok().message("当前剧本已处于停用状态(调试)");
    }

    @Action
    public R showAST(HttpServletRequest request) throws Exception {
        String scripts = RequestUtils.getStringParameter(request, "scripts");
        Long bandId = RequestUtils.getLongParameter(request, "bandId");
        List<RunScriptVo> runScriptVoList = getRunScriptVo(scripts, -1);
        ScriptService scriptService = getBean(ScriptService.class);
        Map<String,Object> showASTResult = scriptService.showAST(runScriptVoList, objIdToBandId(bandId));
        return R.ok().put(showASTResult);
    }
// --------------------------------------------------------------------------------------------------

    /*
     * 剧本草稿
     * */
    @BeanDeclare(forClass = DraftService.class, scope = BeanScope.GLOBAL)
    private DraftService onDeclaringDraftService() {
        return new DraftServiceImpl();
    }

    @BeanDeclare(forClass = DraftDao.class, scope = BeanScope.GLOBAL)
    private DraftDao onDeclaringDraftDao() throws Exception {
        return new DraftDaoImpl();
    }

    /*
     * 分析剧本
     * */
    @BeanDeclare(forClass = AnalyseService.class, scope = BeanScope.GLOBAL)
    private AnalyseService onDeclaringAnalyseService() {
        return new AnalyseServiceImpl();
    }

    @BeanDeclare(forClass = AnalyseDao.class, scope = BeanScope.GLOBAL)
    private AnalyseDao onDeclaringAnalyseDao() throws Exception {
        return new AnalyseDaoImpl();
    }

    /*
     * G4
     * */
    @BeanDeclare(forClass = G4Service.class, scope = BeanScope.GLOBAL)
    private G4Service onDeclaringG4Service() {
        return new G4ServiceImpl();
    }

    @BeanDeclare(forClass = G4Dao.class, scope = BeanScope.GLOBAL)
    private G4Dao onDeclaringG4Dao() throws Exception {
        return new G4DaoImpl();
    }

    /*
     * 分析剧本运行记录表
     * */
    @BeanDeclare(forClass = HistoryRecordService.class, scope = BeanScope.GLOBAL)
    private HistoryRecordService onDeclaringHistoryRecordService() {
        return new HistoryRecordServiceImpl();
    }

    @BeanDeclare(forClass = HistoryRecordDao.class, scope = BeanScope.GLOBAL)
    private HistoryRecordDao onDeclaringHistoryRecordDao() throws Exception {
        return new HistoryRecordDaoImpl();
    }

    /*
     * 操作日志记录表
     * */
    @BeanDeclare(forClass = ActionLogService.class, scope = BeanScope.GLOBAL)
    private ActionLogService onDeclaringActionLogService() {
        return new ActionLogServiceImpl();
    }

    @BeanDeclare(forClass = ActionLogDao.class, scope = BeanScope.GLOBAL)
    private ActionLogDao onDeclaringActionLogDao() throws Exception {
        return new ActionLogDaoImpl();
    }


    /*
     *  核心接口
     * */
    @BeanDeclare(forClass = CoreRemoteService.class, scope = BeanScope.GLOBAL)
    private CoreRemoteService onDeclaringCoreRemoteService() {
        return new CoreRemoteServiceImpl();
    }

    /*
     *  剧本调试运行
     * */
    @BeanDeclare(forClass = ScriptService.class, scope = BeanScope.TEMPORY)
    private ScriptService onDeclaringScriptService() {
        return new ScriptServiceImpl();
    }

    /*
     * 自定义线程池组
     * */
    @BeanDeclare(forClass = ThreadPoolGroup.class, scope = BeanScope.GLOBAL)
    private ThreadPoolGroup onDeclaringThreadPoolGroup() {
        return new ThreadPoolGroup();
    }


    /*
     * 自定义RabbitMQ
     * */
    @BeanDeclare(forClass = MyMQ.class, scope = BeanScope.GLOBAL)
    private MyMQ onDeclaringMyMQ() throws Exception {
        return new MyMQ();
    }

    /**
     * Jedis 工具类
     */
    @BeanDeclare(forClass = JedisUtil.class, scope = BeanScope.GLOBAL)
    private JedisUtil onDeclaringJedisUtil() {
        return new JedisUtil();
    }

    /*
     * 消息工具远程服务
     * */
    @BeanDeclare(forClass = IMessageToolRemoteService.class, scope = BeanScope.TEMPORY)
    private IMessageToolRemoteService onDeclaringMessageToolRemoteService() {
        return new MessageToolRemoteServiceImpl(){
            @Override
            protected String getAccessToken() throws Exception {
                // 暂时以机器人(子豪账户)的身份通知
                return BandCore.getAccessToken();
            }
        };
    }

    /*
     * 帮区元素名称远程服务
     * */
    @BeanDeclare(forClass = AllEnvironmentService.class, scope = BeanScope.TEMPORY)
    private AllEnvironmentService onDeclaringAllEnvironmentService() {
        return new AllEnvironmentServiceImpl();
    }

}
